package com.itheima.edu.info.subwaymanager.ioutil;

import com.itheima.edu.info.subwaymanager.domain.Subway;

import java.io.*;
import java.util.ArrayList;

/**
 * @Author 王加鑫
 * @Date 2021/5/23 19:57
 * @Version 1.0
 * Subway.txt文件的IO流操作
 */
public class SubwayIOUtil {

    /**
     * 读取Subway.txt文件
     * @param
     * @return
     */
    public static ArrayList<Subway> readMessage(){
        BufferedReader bufferedReader = null;
        ArrayList<Subway> subways = new ArrayList<>();
        try {
            bufferedReader = new BufferedReader(new FileReader("itheima-edu-info- subwaymanager/subways.txt"));
            String readLine ;
            while ((readLine = bufferedReader.readLine())!= null){
                String[] subwayArr = readLine.split(",");
                subways.add(new Subway(subwayArr[0],subwayArr[1],subwayArr[2]));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return subways;
    }

    public static void writeMessage(Subway subway){
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter("itheima-edu-info- subwaymanager/subways.txt",true));
            ArrayList<Subway> subways = readMessage();
            if(subways.size() == 0){
                bufferedWriter.write(subway.getId() + "," + subway.getName() + "," + subway.getLine());
                return;
            }
            bufferedWriter.newLine();
            bufferedWriter.write(subway.getId() + "," + subway.getName() + "," + subway.getLine());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
